// pages/container/confirm-order-details/confirm-order-details.js
const tool = require("../../../utils/util.js");
const server = require("../../../utils/server.js");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageShow: false,
    isIPhoneX: app.globalData.isIPhoneX,
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const _this = this;
    const confirmOrderData = JSON.parse(options.confirmOrderData);
    const goodsInfo = confirmOrderData.data;
    const userInfo = wx.getStorageSync('userInfo');
    let param;

    // 判断是从商品详情过来的 
    if (confirmOrderData.from == "goodsDetails") {
      if (confirmOrderData.chooseBuyMethod == 1) {
        // 选择月定制卖法
        let sum = 0;
        for (var i = 0; i < goodsInfo.serializeMonth.length; i++) {
          sum += goodsInfo.serializeMonth[i].count;
          goodsInfo.serializeMonth[i].num = goodsInfo.serializeMonth[i].count
        }
        param = {
          order_label: confirmOrderData.chooseBuyMethod,
          member_id: userInfo.member_id,
          goods_id: goodsInfo.goods_id,
          sp_value_id: goodsInfo.spec[goodsInfo.defaultSpecIndex].sp_value_id,
          sum: sum,
          monthlist: JSON.stringify(goodsInfo.serializeMonth)
        };

      } else if (confirmOrderData.chooseBuyMethod == 0){
        param = {
          member_id: userInfo.member_id,
          order_label: confirmOrderData.chooseBuyMethod,
          ifcart: 'collocation',
          collocation_list: JSON.stringify(goodsInfo)
        }
      } else {

        //拼团，众筹
        param = {
          member_id: userInfo.member_id,
          order_label: confirmOrderData.chooseBuyMethod,
          goods_id: goodsInfo[0].goods_id,
          sp_value_id: goodsInfo[0].sp_value_id,
          num: goodsInfo[0].num,
        }
      }
      if (options.type == "share"){
        _this.setData({
          shareParam :{
            type: "share",
            cantuanid: options.cantuanid
          }
        })
      }
    } else {
      //从购物车选择商品
      param = {
        member_id: userInfo.member_id,
        ifcart: 1,
        cart_info: confirmOrderData.data
      }
    }
    _this.setData({
      param: param,
      userInfo: userInfo
    })
    _this.loadPage(param);
  },

  loadPage: function(param) {
    const _this = this;
    server.postJSON("/index/buy/buy_step1", param, function(res) {
      _this.setData({
        pageShow: true
      });
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      if (param.ifcart == 1) {
        for (var i = 0; i < res.data.data.goods_list.length; i++) {
          res.data.data.goods_list[i].num = res.data.data.goods_list[i].goods_num;
        }
        _this.setData(res.data.data);
      } else {
        res.data.data.sprice = res.data.data.address_info ? res.data.data.sprice : 0; 
        _this.setData(res.data.data);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var query = wx.createSelectorQuery()
    this.freight = this.selectComponent("#freight");
  },
  // 显示运费弹窗
  showfreight: function() {
    if (this.data.address_info) {
      this.freight.showDialog();
    } else {
      tool.warning("请先选择收货地址");
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const _this = this;
    let changeAddress = app.globalData.changeAddress;
    if (changeAddress && changeAddress.isChange) {
      console.log(changeAddress)
      let param = _this.data.param;
      param.address_id = changeAddress.addressInfo.address_id;
      app.globalData.changeAddress = null;
      _this.loadPage(param);
    }

  },
  // 获取备注留言
  _messageChange: function(e) {
    tool.changInput(e,this);
  },
  createOrder: function () {
    const _this = this;
    // 防止短时间多次提交 时间间隔5000ms
    if (!tool.lockClick()) {

      return;
    }
    if (_this.data.is_paisong == 'B') {
      tool.warning("抱歉，该地区无配送。");
      return;
    }
    
    if (!(_this.data.address_info && _this.data.address_info.address_id)) {
      tool.warning("请先选择收货地址");
      return;
    }
    let param = {
      member_id: _this.data.param.member_id,
      order_amount: _this.data.order_amount,
      goods_amount: _this.data.goods_amount,
      order_message: _this.data.message ? _this.data.message : "",
      address_id: _this.data.address_info.address_id,
      spice: _this.data.sprice
    };
    if (_this.data.param.ifcart == 1) {
      param.ifcart =  1;
      param.cart_info =  _this.data.param.cart_info;
    } else {
      param.order_label = _this.data.order_label;
      if (_this.data.order_label == 1) {
        param.goods_id = _this.data.goods_list[0].goods_id;
        let monthlist = _this.data.goods_list[0].monthlist;
        for (var i = 0; i < _this.data.goods_list[0].monthlist.length; i++) {
          monthlist[i].month_book_price = _this.data.goods_list[0].goods_price
          monthlist[i].sp_value_id = _this.data.goods_list[0].sp_value_id
        }
        monthlist = JSON.stringify(monthlist);
        param.monthlist = monthlist;
        param.spec = _this.data.goods_list[0].spec_name;
      } else if (_this.data.order_label == 0) {
        let collocation_list = [];
        param.ifcart = "collocation";
        for(var i = 0; i < _this.data.goods_list.length; i++) {
          collocation_list.push({
            goods_id: _this.data.goods_list[i].goods_id,
            is_collocation: _this.data.goods_list[i].is_collocation,
            num: _this.data.goods_list[i].num,
            sp_value_id: _this.data.goods_list[i].sp_value_id,
            sprice: _this.data.goods_list[i].sprice,
          })
        }
        param.collocation_list = JSON.stringify(collocation_list);
      } else if (_this.data.order_label == 2 || _this.data.order_label == 3) {
        param.goods_id = _this.data.goods_list[0].goods_id;
        param.num = _this.data.goods_list[0].num;
        param.sp_value_id = _this.data.goods_list[0].sp_value_id;
      }
      
    }
    if (_this.data.shareParam && _this.data.shareParam.type == "share" && _this.data.order_label == 2){
      param.cantuanid = _this.data.shareParam.cantuanid
    }

    server.postJSON("/index/buy/buy_step2", param, function(res) {
      if (res.data.error != 0) {
        tool.warning(res.data.message);
        return;
      }
      _this.toPay(res.data.data);
    })
  },
  /**
 * 是否使用钱包支付
 */
  switchChange: function (e) {
    const _this = this;
    var isWalletPay = e.detail.value;
    if (_this.data.available_rc_balance <= 0) {
      isWalletPay = false;
    }
    this.setData({
      isWalletPay: isWalletPay
    })
  },
  // 调起支付
  toPay: function(orderInfo) {
    const _this = this;
    let param = {
      member_id: _this.data.userInfo.member_id,
      address_id: _this.data.address_info.address_id,
      all_no: orderInfo.all_no,
      order_label: orderInfo.order_label,
      openid: _this.data.userInfo.openid
    };
    if (_this.data.isWalletPay) {
      param.is_wallet = 2;
      wx.showModal({
        title: '提示',
        content: '您将使用钱包支付',
        success: function (res) {
          if(res.confirm) {
            applyPay(param);
          } else {
            tool.warning("支付失败");
            wx.navigateTo({
              // url: '/pages/container/order-details/order-details?all_no=' + orderInfo.all_no+"&order_label="+ orderInfo.order_label,
              url: '/pages/container/order-details/goods-to-pay/goods-to-pay?all_no=' + orderInfo.all_no + "&order_label=" + orderInfo.order_label
            });
          }
        }
      });
    } else {
      param.is_wallet = 1;
      applyPay(param);
    }
    function applyPay(param) {
      server.postJSON("/index/Wxpay/index", param, function (res) {
        if (res.data.error != 0) {
          tool.warning(res.data.message);
          return;
        }
        if (res.data.data.order_state == 20) {
          tool.success('支付成功');
          setTimeout(function () {
            wx.switchTab({
              // url: '/pages/container/order-details/order-details?all_no=' + param.all_no + "&order_label=" + param.order_label
              url: '/pages/container/order-list/order-list'
            });
          }, 1000);
          return;
        }
        wx.requestPayment({
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          package: res.data.data.package,
          signType: 'MD5',
          paySign: res.data.data.paySign,
          success: function (r) {
            if (r.errMsg == "requestPayment:ok") {
              wx.switchTab({
                // url: '/pages/container/order-details/order-details?all_no=' + orderInfo.all_no + "&order_label=" + orderInfo.order_label
                url: '/pages/container/order-list/order-list'
              });
            }
          },
          fail: function (res) {
            tool.warning("支付失败");
            wx.navigateTo({
              // url: '/pages/container/order-details/order-details?all_no=' + orderInfo.all_no+"&order_label="+ orderInfo.order_label,
              url: '/pages/container/order-details/goods-to-pay/goods-to-pay?all_no=' + orderInfo.all_no + "&order_label=" + orderInfo.order_label
            });

          }
        });
      });
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})